package com.example.messagesdkdemo;

import android.util.Log;
import android.view.View;
import android.widget.Toast;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;

public class ByteBuddyHook {

    public static void hookOnClickListener(final View view) {
        new ByteBuddy()
                .redefine(view.getClass())
                .method(ElementMatchers.isMethod().and(ElementMatchers.takesArguments(TypeDescription.ForLoadedType.of(View.class))))
                .intercept(Advice.to(ClickAdvice.class))
                .make()
                .load(view.getClass().getClassLoader(), ClassLoadingStrategy.Default.INJECTION);
    }

    public static class ClickAdvice {
        @Advice.OnMethodEnter
        public static void onEnter(@Advice.This View view, @Advice.Argument(0) View clickedView) {
            if (view.getId() == R.id.btn_delete) {
                Toast.makeText(view.getContext(), "Enhanced Click Event", Toast.LENGTH_SHORT).show();
            }
        }
    }

//    public static void hook() {
//// 创建一个动态类
////        Class<?> enhancedClass = new ByteBuddy()
////                .subclass(View.class)
////                .method(ElementMatchers.named("doSomething"))
////                .intercept(Advice.to(YourMethodAdvice.class))
////                .make()
////                .load(View.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
////                .getLoaded();
////
////        // 创建类的实例
////        View instance = (View)enhancedClass.getDeclaredConstructor().newInstance();
////
////        // 调用方法
////        instance.setOnClickListener();
//
//        new ByteBuddy()
//                .redefine(View.class) // 需要修改的类
//                .method(ElementMatchers.named("setOnClickListener")) // 需要修改的方法
//                .intercept(Advice.to(YourMethodAdvice.class)) // 这里的 YourMethodAdvice 是你的自定义逻辑
//                .make()
//                .load(View.class.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST);
//    }
//
//    public static class YourMethodAdvice {
//        @Advice.OnMethodEnter
//        public static void onEnter() {
//            // 自定义逻辑：方法调用之前执行
//            Log.e("TAG","Method is about to be called");
//        }
//
//        @Advice.OnMethodExit
//        public static void onExit() {
//            // 自定义逻辑：方法调用之后执行
//            Log.e("TAG","Method has been called");
//        }
//    }
}

